package org.jeecg.qis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.qis.entity.QisMatdetailValue;
import org.jeecg.qis.entity.QisMatheadValue;
import org.jeecg.qis.entity.QisRuleCfg;
import org.jeecg.qis.mapper.QisMatdetailValueMapper;
import org.jeecg.qis.mapper.QisMatheadValueMapper;
import org.jeecg.qis.mapper.QisRuleCfgMapper;
import org.jeecg.qis.service.IQisMatheadValueService;
import org.jeecg.qis.vo.QisInspectionItemsVO;
import org.jeecg.qis.vo.QisMatheadValueVO;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description: qis-来料检测送检单数据表
 * @Author: shaolong
 * @Date: 2022-10-09
 * @Version: V1.0
 */
@Service
public class QisMatheadValueServiceImpl extends ServiceImpl<QisMatheadValueMapper, QisMatheadValue> implements IQisMatheadValueService {

	@Autowired
	private QisMatheadValueMapper qisMatheadValueMapper;
	@Autowired
	private QisMatdetailValueMapper qisMatdetailValueMapper;
	@Autowired
	private QisRuleCfgMapper qisRuleCfgMapper;
	@Lazy
	@Resource
	private CommonAPI commonApi;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		qisMatdetailValueMapper.deleteByMainId(id);
		qisMatheadValueMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for (Serializable id : idList) {
			qisMatdetailValueMapper.deleteByMainId(id.toString());
			qisMatheadValueMapper.deleteById(id);
		}
	}

	@Override
	public Result<String> edit(QisMatheadValue qisMatheadValue) {
		LambdaUpdateWrapper<QisMatheadValue> eq = new LambdaUpdateWrapper<QisMatheadValue>();
		eq.eq(QisMatheadValue::getRecId, qisMatheadValue.getRecId());
		boolean update = update(qisMatheadValue, eq);
		return update ? Result.ok("修改成功!") : Result.error("修改失败!");
	}

	@Override
	public void qisMaInspectionSubmission(QisMatheadValue qisMatheadValue) {

	}

	@Override
	public IPage<QisMatheadValueVO> queryList(Page<QisMatheadValueVO> page, QisMatheadValue qisMatheadValue) {
		return this.baseMapper.queryList(page, qisMatheadValue);
	}

	@Override
	public Map<String, Object> getInspectionItems(QisMatheadValue qisMatheadValue) {
		Map<String, Object> map = new HashMap<>();
		//1.根据检验单号查出对应定性项目列表并排序
		List<QisInspectionItemsVO> qualitativeItems = this.baseMapper.getQualitativeItems(qisMatheadValue);
		//2.根据检验单号查出对应定量项目列表并排序
		List<QisInspectionItemsVO> quantitativeItems = this.baseMapper.getQuantitativeItems(qisMatheadValue);
		map.put("qualitativeItems", qualitativeItems);
		map.put("quantitativeItems", quantitativeItems);
		return map;
	}

    @Override
    @Transactional(rollbackFor = Exception.class)
	public void createCheckSheet(QisMatheadValue qisMatheadValue) {
        //1.查询对应检验项目列表
        qisMatheadValue.setResult("2");
        this.baseMapper.updateById(qisMatheadValue);
        List<QisMatdetailValue> inspectionList = this.baseMapper.getInspectionList(qisMatheadValue.getRecId());
		AtomicInteger j = new AtomicInteger(100);
		AtomicInteger x = new AtomicInteger(200);
        //2.遍历检验项目如果定性项目直接存 如果定量项目则按照抽样方案数生成样本数
        inspectionList.forEach(item -> {
            if ("1".equals(item.getDataType())) {
                //Integer counterValue = commonApi.getCounterValue("recId.qis_matdetail_value");
                item.setRecId(commonApi.getCounterValue("recId.qis_matdetail_value","0"));
                qisMatdetailValueMapper.insert(item);
            } else {
                List<QisRuleCfg> qisRuleCfgs = qisRuleCfgMapper.selectList(new LambdaQueryWrapper<QisRuleCfg>().eq(QisRuleCfg::getGroupid, item.getGroupId()));
                if (qisRuleCfgs.size() > 1) {
					BigDecimal qty = qisMatheadValue.getQty();
					AtomicInteger num = new AtomicInteger();
					qisRuleCfgs.forEach(item2 -> {
                        if (item2.getLowLimit().compareTo(qty) <= 0 && item2.getUpLimit().compareTo(qty) >= 0) {
                            num.set(item2.getValue().intValue());
                        }
                    });
                    for (int i = 1; i <= num.get(); i++) {
                        item.setSampleNum(String.valueOf(i));
						item.setRecId(commonApi.getCounterValue("recId.qis_matdetail_value","0"));
                        qisMatdetailValueMapper.insert(item);
                    }
                } else if (qisRuleCfgs.size() == 1) {
                    QisRuleCfg qisRuleCfg = qisRuleCfgs.get(0);
                    int value = qisRuleCfg.getValue().intValue();
                    for (int i = 1; i <= value; i++) {
                        item.setSampleNum(String.valueOf(i));
						item.setRecId(commonApi.getCounterValue("recId.qis_matdetail_value","0"));
                        qisMatdetailValueMapper.insert(item);
                    }
                } else {
                    new Exception("未配置规则");
                }
            }
        });

    }

    @Override
    public List<QisMatdetailValue> getQuantitativeDetail(Map<String, Object> map) {
        return this.baseMapper.getQuantitativeDetail(map);
    }


    @Override
    public Result<String> verificationInspection(QisMatheadValue qisMatheadValue) {
        //1.查出所有子明细判断是否检测完毕 如完毕则判断是否检验完成
        QisMatheadValue byId = this.getById(qisMatheadValue.getRecId());
        qisMatdetailValueMapper.selectList(new LambdaQueryWrapper<>());
        return null;
    }

	@Override
	public void addQisMatheadValue(QisMatheadValue qisMatheadValue) {
		//1获取主键
		Integer counterValue = commonApi.getCounterValue("recId.qis_mathead_value","0");
		qisMatheadValue.setRecId(counterValue);
		qisMatheadValue.setCheckTyp("2");
		qisMatheadValue.setResult("3");
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		qisMatheadValue.setUser(sysUser.getRealname());
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String formattedDate = sdf.format(now);
		Integer counterValue2 = commonApi.getCounterValue("checkno.qis_mathead_value","0");
		qisMatheadValue.setChecklistno("MC"+formattedDate+counterValue2);
		//2生成检验单号
		this.save(qisMatheadValue);
	}
}
